import request from '@/utils/request/axios';
import { transformDataToFormData } from '@/utils/request/paramsHandle';
import * as Cookies from 'js-cookie';
import { statusCode } from './statusCode';
import moment from 'moment';
import { Message } from 'element-ui';

declare interface IRtnType<T = any> {
  code: number;
  message: string;
  data: T;
  timestamp?: number;
}

// 扩展名 : MIME类型
const FileType: any = {
  doc: 'application/msword',
  docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
  xls: 'application/vnd.ms-excel',
  xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
  csv: 'text/csv',
  ppt: 'application/vnd.ms-powerpoint',
  pptx: 'application/vnd.openxmlformats-officedocument.presentationml.presentation',
  jpeg: 'image/jpeg',
  jpg: 'image/jpeg',
  png: 'image/png',
  rar: 'application/x-rar-compressed',
  pdf: 'application/pdf',
  zip: 'application/zip',
  ofd: 'application/ofd',
};

/**
 * post 请求
 * @url  url [请求链接]
 * @params  params [参数]
 * @params  fn [回调函数]
 * @return [返回值]
 */
export function post(url: string, params: any, fn: any = function (_e) {}, isLoading: boolean = true) {
  return request.post(url, params, fn, isLoading);
}

/**
 * get 请求
 * @url  url [请求链接]
 * @params  params  [参数]
 * @params  fn [回调函数]
 * @return [返回值]
 */
export function get(url: any, params: any, fn: any = function (_e) {}, isLoading: boolean = true) {
  return request.get(url, params, fn, isLoading);
}

/**
 * 下载 请求
 * @url  url [请求链接]
 * @params  params [参数]
 * @params  allowUnToken [是否允许为空]
 * @params  fn [回调函数]
 * @return [返回值]
 */
export async function fileDownload(url: any, params: any, allowUnToken?: boolean) {
  const rtn: IRtnType = {
    code: 90004,
    message: statusCode[90004],
    data: {},
  };

  // 判断 参数是否为空
  if (!params) {
    params = {};
  }
  try {
    const rtnData: any = await request.download(url, params, (config: any) => {
      const contentType = config.headers['content-type']; //返回流类型
      if (contentType.startsWith('application/json')) {
        const file = new FileReader(); //读取文件
        file.readAsText(config.data, 'utf-8'); //读取文件，并设置编码格式为utf-8
        file.onload = function () {
          //在读取文件操作完成后触发
          const result = JSON.parse(file.result as any); //reader.result返回文件的内容，只在读取操作完成后有效
          Message.error(result.message);
        };
        return;
      }
      // 返回文件名
      let contentDisposition = config.headers['content-disposition'];
      if (!contentDisposition) {
        const time = new Date();
        contentDisposition = `;filename=未命名_${moment(time).valueOf()}.xlsx`;
      }
      const fileName = window.decodeURI(contentDisposition.split(`filename=`)[1]);

      // 文件类型
      const suffix: string = fileName.split('.')[1];
      let type: string = FileType[suffix];

      if (!type) {
        type = FileType.zip;
      }

      const link = document.createElement('a');
      const blob = new Blob([config.data], {
        type: FileType[suffix],
      });
      const time = new Date();
      link.style.display = 'none';
      link.href = URL.createObjectURL(blob); //创建url对象
      link.download = fileName; //下载后文件名
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      URL.revokeObjectURL(link.href); //销毁url对象
    });

    if (rtnData.data) {
      rtn.code = 2000;
      rtn.message = statusCode[2000];
    } else {
      rtn;
    }
  } catch (error) {
    console.error('fileDownload 请求异常 >>>>>>>>：', error);
  }
  return rtn;
}
